import instance from '@/utils/request'
import { addGoods, delGoods } from '@/api/cart.js'
// import { getUserDefaultAddress } from '@/utils/userDefaultAddressLocal'
import store from '..'
export default {
  namespaced: true,
  state () {
    return {
      cartList: [] // 购物车全部列表信息
      // userDefaultAddress: getUserDefaultAddress // 用户默认收货地址
    }
  },
  mutations: {
    // 存入购物车列表
    setCartList (state, arr) {
      state.cartList = arr
    },
    setCartNum (state, num) {
      state.cartNum = num
    },
    // 管理是否选中
    handleSelected (state, id) {
      const temp = state.cartList.find(item => item.goods_id === id)
      temp.isChecked = !temp.isChecked
    },
    // 商品 (全选 / 全不选)
    allGoodsSelected (state, isAllChecked) {
      state.cartList.forEach(item => { item.isChecked = isAllChecked })
    },
    // 客户端增减商品到购物车
    setLocalNum (state, obj) {
      const { goodsId, goodsNum } = obj
      state.cartList.find(item => item.goods_id === goodsId).goods_num = goodsNum
    },
    // 存入用户默认收货地址
    setDefaultAddress (state, obj) {
      state.userDefaultAddress = obj
    }
  },
  actions: {
    // 异步获取购物车列表
    async getCartAction (context) {
      const { data } = await instance({
        url: '/cart/list',
        headers: {
          'Access-Token': store.getters.isLogin,
          platform: 'H5'
        }
      })
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
      context.commit('setCartNum', data.cartTotal)
      console.log(data)
    },
    // 异步增减商品到购物车
    async addGoods (context, obj) {
      const { goodsId, goodsNum, goodsSkuId } = obj
      context.commit('setLocalNum', { goodsId, goodsNum })
      const result = await addGoods(goodsId, goodsNum, goodsSkuId)
      console.log(result)
    },
    // 删除购物车中商品
    delGoods (context) {
      const ids = context.getters.selectedGoods.map(item => item.id)
      delGoods(ids)
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 求商品总数
    goodsNum (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 已选中的商品
    selectedGoods (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    // 已选中商品的总数
    selGoodsNum (state, getters) {
      return getters.selectedGoods.reduce((sum, item) => sum + item.goods_num, 0)
    },
    // 已选中商品的总价
    selGoodsPrice (state, getters) {
      return getters.selectedGoods.reduce((sum, item) => sum + item.goods_num * item.goods.goods_price_min, 0).toFixed(2)
    },
    // 判断是否全选
    isAllChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  }
}
